#include "../ser/server.hpp"
#include <fstream>
#include <sys/stat.h>
#include <regex>
// #include"../ser/Log.hpp"

#define DELETE_TIEMOUT 10

class Util
{
public:
    // 字符串分割函数
    static size_t Split(const std::string &str, const std::string &delim, std::vector<std::string> *res)
    {
        size_t offset = 0;
        while (offset < str.size())
        {
            size_t pos = str.find(delim, offset);
            if (pos == std::string::npos) // 未找到分隔符，则将剩余字符串全部添加到结果中
            {
                if (pos == str.size())
                    break; // 防止空字符串的情况
                res->push_back(str.substr(offset));
                return res->size();
            }
            if (pos > offset)
                res->push_back(str.substr(offset, pos - offset)); // 找到分隔符，将前面字符串添加到结果中
            offset = pos + delim.size();
        }
        return res->size();
    }
    // 读取文件内容
    static bool ReadFile(const std::string &path, std::string *buf)
    {
        std::ifstream ifs(path, std::ios::binary);
        if (ifs.is_open() == false)
        {
            printf("open file %s failed\n", path.c_str());
            return false;
        }
        size_t size = 0;
        ifs.seekg(0, std::ios::end); // 跳过读写位置到末尾
        size = ifs.tellg();          // 获取当前读位置相对于起始位置的偏移量，从末尾偏移刚好就是文件大小
        ifs.seekg(0, std::ios::beg); // 跳转到起始位置
        buf->resize(size);           // 开辟文件大小的空间
        ifs.read(&(*buf)[0], size);
        if (ifs.good() == false)
        {
            printf("read file %s failed\n", path.c_str());
            ifs.close();
            return false;
        }
        ifs.close();
        return true;
    }
    // 向文件写入内容
    static bool WriteFile(std::string &filename, const std::string &buf)
    {
        std::ofstream ofs(filename, std::ios::binary | std::ios::trunc);
        if (ofs.is_open() == false)
        {
            printf("open file %s failed\n", filename.c_str());
            return false;
        }
        ofs.write(buf.c_str(), buf.size());
        if (ofs.good() == false)
        {
            // printf("write file %s failed\n",filename.c_str());
            LOG_ERROR("write file %s failed", filename.c_str());
            ofs.close();
            return false;
        }
        return true;
    }
    // URL编码
    static std::string UrlEncode(const std::string &url, bool convert_space_to_plus)
    {
        std::string res;
        for (auto c : url)
        {
            if (isalnum(c) || c == '-' || c == '_' || c == '.' || c == '~' || c == '/' || c == ':' || c == '@' || c == '&' || c == '=' || c == '+')
            {
                res += c; // 保留字符
                continue;
            }
            if (convert_space_to_plus && c == ' ')
            {
                res += '+'; // 转换空格为+
                continue;
            }
            // 剩下的字符都是需要编码为%HH的格式
            char buf[4] = {0};
            // snprintf与printf比较类似，都是格式化字符串，只不过一个是打印，一个是存储
            snprintf(buf, 4, "%%%02X", c);
            res += buf;
        }
        return res;
    }

    static char HEXTOI(char c)
    {
        if (c >= '0' && c <= '9')
        {
            return c - '0';
        }
        if (c >= 'a' && c <= 'z')
        {
            return c - 'a' + 10;
        }
        if (c >= 'A' && c <= 'Z')
        {
            return c - 'A' + 10;
        }
        return 0;
    }
    // URL解码
    static std::string UrlDecode(const std::string &url, bool convert_plus_to_space)
    {
        std::string res;
        for (auto i = 0; i < url.size(); i++)
        {
            if (url[i] == '%')
            {
                char v1 = HEXTOI(url[i + 1]);
                char v2 = HEXTOI(url[i + 2]);
                char v = (v1 << 4) + v2;
                res += v;
                i += 2;
            }
            else if (convert_plus_to_space && url[i] == '+')
            {
                res += ' ';
            }
            else
            {
                res += url[i];
            }
        }
        return res;
    }
    // 响应状态码的描述信息获取
    static std::string StatuDesc(int status)
    {
        std::unordered_map<int, std::string> desc_map = {
            {100, "Continue"},
            {101, "Switching Protocol"},
            {102, "Processing"},
            {103, "Early Hints"},
            {200, "OK"},
            {201, "Created"},
            {202, "Accepted"},
            {203, "Non-Authoritative Information"},
            {204, "No Content"},
            {205, "Reset Content"},
            {206, "Partial Content"},
            {207, "Multi-Status"},
            {208, "Already Reported"},
            {226, "IM Used"},
            {300, "Multiple Choice"},
            {301, "Moved Permanently"},
            {302, "Found"},
            {303, "See Other"},
            {304, "Not Modified"},
            {305, "Use Proxy"},
            {306, "unused"},
            {307, "Temporary Redirect"},
            {308, "Permanent Redirect"},
            {400, "Bad Request"},
            {401, "Unauthorized"},
            {402, "Payment Required"},
            {403, "Forbidden"},
            {404, "Not Found"},
            {405, "Method Not Allowed"},
            {406, "Not Acceptable"},
            {407, "Proxy Authentication Required"},
            {408, "Request Timeout"},
            {409, "Conflict"},
            {410, "Gone"},
            {411, "Length Required"},
            {412, "Precondition Failed"},
            {413, "Payload Too Large"},
            {414, "URI Too Long"},
            {415, "Unsupported Media Type"},
            {416, "Range Not Satisfiable"},
            {417, "Expectation Failed"},
            {418, "I'm a teapot"},
            {421, "Misdirected Request"},
            {422, "Unprocessable Entity"},
            {423, "Locked"},
            {424, "Failed Dependency"},
            {425, "Too Early"},
            {426, "Upgrade Required"},
            {428, "Precondition Required"},
            {429, "Too Many Requests"},
            {431, "Request Header Fields Too Large"},
            {451, "Unavailable For Legal Reasons"},
            {501, "Not Implemented"},
            {502, "Bad Gateway"},
            {503, "Service Unavailable"},
            {504, "Gateway Timeout"},
            {505, "HTTP Version Not Supported"},
            {506, "Variant Also Negotiates"},
            {507, "Insufficient Storage"},
            {508, "Loop Detected"},
            {510, "Not Extended"},
            {511, "Network Authentication Required"}};
        auto it = desc_map.find(status);
        if (it == desc_map.end())
        {
            return "Unknown";
        }
        return it->second;
    }
    // 根据文件后缀名获取文件mime
    static std::string ExtMime(std::string ext)
    {
        std::unordered_map<std::string, std::string> mime_map = {
            {".html", "text/html"},
            {".css", "text/css"},
            {".js", "application/javascript"},
            {".png", "image/png"},
            {".jpg", "image/jpeg"},
            {".gif", "image/gif"},
            {".svg", "image/svg+xml"},
            {".ttf", "application/x-font-ttf"},
            {".woff", "application/font-woff"},
            {".woff2", "font/woff2"},
            {".eot", "application/vnd.ms-fontobject"},
            {".otf", "font/otf"},
            {".ico", "image/x-icon"},
            {".json", "application/json"},
            {".xml", "application/xml"},
            {".txt", "text/plain"},
            {".pdf", "application/pdf"},
            {".zip", "application/zip"},
            {".tar", "application/x-tar"},
            {".gz", "application/x-gzip"},
            {".mp3", "audio/mpeg"},
            {".mp4", "video/mp4"},
            {".avi", "video/x-msvideo"},
            {".mov", "video/quicktime"},
            {".wmv", "video/x-ms-wmv"},
            {".flv", "video/x-flv"},
            {".swf", "application/x-shockwave-flash"},
            {".psd", "image/vnd.adobe.photoshop"},
            {".doc", "application/msword"},
            {".docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"},
            {".xls", "application/vnd.ms-excel"},
            {".xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"},
            {".ppt", "application/vnd.ms-powerpoint"},
            {".pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation"}};
        size_t pos = ext.find_last_of('.'); // 查找文件后缀名的位置
        if (pos == std::string::npos)
        {
            return "application/octet-stream";
        }
        std::string suffix = ext.substr(pos); // 获取文件后缀名
        auto it = mime_map.find(suffix);
        if (it == mime_map.end())
        {
            return "application/octet-stream";
        }
        return it->second;
    }
    // 判断一个文件是否是一个目录
    static bool IsDirectory(const std::string filename)
    {
        struct stat st;
        int ret = stat(filename.c_str(), &st);
        if (ret < 0)
        {
            return false;
        }
        return S_ISDIR(st.st_mode);
    }
    // 判断一个文件是否是一个普通文件
    static bool IsRegularFile(const std::string filename)
    {
        struct stat st;
        int ret = stat(filename.c_str(), &st);
        if (ret < 0)
        {
            return false;
        }
        return S_ISREG(st.st_mode);
    }
    // http请求的资源路径有效性判断
    static bool IsValidPath(const std::string &path)
    {
        std::vector<std::string> subdir;
        Split(path, "/", &subdir);
        int level = 0;
        for (auto &s : subdir)
        {
            if (s == "..")
            {
                level--;
                if (level < 0)
                    return false;
            }
            else
            {
                level++;
            }
        }
        return true;
    }
};

class HttpRequest
{
public:
    std::string _method;                                   // 请求方法
    std::string _path;                                     // 资源路径
    std::string _version;                                  // http版本
    std::string _body;                                     // 请求正文
    std::smatch _matchs;                                   // 资源路径的正则提取数据
    std::unordered_map<std::string, std::string> _headers; // 请求头
    std::unordered_map<std::string, std::string> _params;  // 请求参数
public:
    HttpRequest() : _version("HTTP/1.1") {}

    void ReSet()
    {
        _method.clear();
        _path.clear();
        _version = "HTTP/1.1";
        _body.clear();
        std::smatch match;
        _matchs.swap(match);
        _headers.clear();
        _params.clear();
    }
    // 插入头部字段
    void SetHeader(const std::string &key, const std::string &value)
    {
        _headers.insert(std::make_pair(key, value));
    }
    // 是否存在头部字段
    bool HasHeader(const std::string &key) const
    {
        auto it = _headers.find(key);
        if (it == _headers.end())
            return false;
        return true;
    }
    // 获取头部字段
    std::string GetHeader(const std::string &key) const
    {
        auto it = _headers.find(key);
        if (it == _headers.end())
            return "";
        return it->second;
    }
    // 设置请求参数
    void SetParam(const std::string &key, const std::string &value)
    {
        _params.insert(std::make_pair(key, value));
    }
    // 是否存在请求参数
    bool HasParam(const std::string &key) const
    {
        auto it = _params.find(key);
        if (it == _params.end())
            return false;
        return true;
    }
    // 获取请求参数
    std::string GetParam(const std::string &key) const
    {
        auto it = _params.find(key);
        if (it == _params.end())
            return "";
        return it->second;
    }
    // 获取正文长度
    size_t ContentLength() const
    {
        bool ret = HasHeader("Content-Length");
        if (ret == false)
            return 0;
        std::string len = GetHeader("Content-Length");
        return std::stoll(len);
    }
    // 判断是否是短连接
    bool Close() const
    {
        // 没有Connection字段，默认是短连接。或者有Connection字段，但值为close，则是短连接，其他都是长连接
        if (HasHeader("Connection") == true && GetHeader("Connection") == "keep-alive")
            return false;
        return true;
    }
};

class HttpReponse
{
public:
    int _status;                                           // 响应状态码
    bool _redirect_flag;                                   // 是否是重定向
    std::string _body;                                     // 响应正文
    std::string _redirect_url;                             // 重定向地址
    std::unordered_map<std::string, std::string> _headers; // 响应头
public:
    HttpReponse() : _status(200), _redirect_flag(false) {}
    HttpReponse(int status) : _status(status), _redirect_flag(false) {}
    void ReSet()
    {
        _status = 200;
        _redirect_flag = false;
        _body.clear();
        _redirect_url.clear();
        _headers.clear();
    }
    void SetHeader(const std::string &key, const std::string &value)
    {
        _headers.insert(std::make_pair(key, value));
    }
    bool HasHeader(const std::string &key)
    {
        auto it = _headers.find(key);
        if (it == _headers.end())
            return false;
        return true;
    }
    std::string GetHeader(const std::string &key)
    {
        auto it = _headers.find(key);
        if (it == _headers.end())
            return "";
        return it->second;
    }
    void SetContent(const std::string &body, std::string type)
    {
        _body = body;
        SetHeader("Content-Type", type);
    }
    void SetRedirect(std::string &url, int status = 302)
    {
        _status = status;
        _redirect_flag = true;
        _redirect_url = url;
    }
    bool Close()
    {
        // 没有Connection字段，默认是短连接。或者有Connection字段，但值为close，则是短连接，其他都是长连接
        if (HasHeader("Connection") == true && GetHeader("Connection") == "keep-alive")
            return false;
        return true;
    }
};

typedef enum
{
    RECV_HTTP_ERROR,
    RECV_HTTP_LINE,
    RECV_HTTP_HEAD,
    RECV_HTTP_BODY,
    RECV_HTTP_OVER
} HttpRecvStatus;

const int Max = 8192;
class HttpContext
{
private:
    int _resp_status;            // 响应状态码
    HttpRecvStatus _recv_status; // 当前接收及解析的阶段状态
    HttpRequest _request;        // 以简析得到的当前请求

private:

    bool ParseHttpLien(const std::string &line)
    {
        std::smatch matchs;
        std::regex pattern("(GET|HEAD|POST|PUT|DELETE|CONNECT|OPTIONS|TRACE) ([^?]*)(?:\\?(.*))? (HTTP/1\\.[01])(?:\r\n|\n)?", std::regex::icase);
        bool ret = std::regex_search(line, matchs, pattern); // 匹配请求行
        if (ret == false)
        {
            _recv_status = RECV_HTTP_ERROR;
            _resp_status = 400;
            std::cout << "No1 match" << std::endl;
            return false;
        }
        // 解析请求方法
        _request._method = matchs[1];
        std::transform(_request._method.begin(), _request._method.end(), _request._method.begin(), ::toupper); // 转换为大写
        // 资源路径的获取，需要进行URL解码
        _request._path = Util::UrlDecode(matchs[2], false);
        // 协议版本的获取
        _request._version = matchs[4];
        // 查询字符串的获取与处理
        std::vector<std::string> queue_string_arry;
        std::string query_string = matchs[3];
        // 查询字符串的格式，以&为分割
        Util::Split(query_string, "&", &queue_string_arry);
        for (auto &str : queue_string_arry)
        {
            size_t pos = str.find("=");
            if (pos == std::string::npos)
            {
                _recv_status = RECV_HTTP_ERROR;
                _resp_status = 400;
                std::cout << "No2 match" << std::endl;
                return false;
            }
            // 进行解码然后赋值
            std::string key = Util::UrlDecode(str.substr(0, pos), false);
            std::string value = Util::UrlDecode(str.substr(pos + 1), false);
            _request.SetParam(key, value);
        }
        return true;
    }
    bool RecvHttpLine(Buffer *buf)
    {
        // std::cout << "RecvHttpLine buf.size:" << buf->readable_size() << std::endl;
        if (_recv_status != RECV_HTTP_LINE)
        {
            return false;
        }
        std::string ret = buf->GetLinePop();
        if (ret.size() == 0)
        {
            if (buf->readable_size() > Max)
            {
                _recv_status = RECV_HTTP_ERROR;
                _resp_status = 415;
                return false;
            }
            return true;
        }
        if (ret.size() > Max)
        {
            _recv_status = RECV_HTTP_ERROR;
            _resp_status = 416;
            return false;
        }
        bool b = ParseHttpLien(ret);
        if (b == false)
        {
            return false;
        }
        // buf->move_read_pos(ret.size()); //读了一行后要进行移动
        _recv_status = RECV_HTTP_HEAD;
        return true;
    }
    
    bool RecvHttpHeader(Buffer *buf)
    {
        if (_recv_status != RECV_HTTP_HEAD)
        {
            return false;
        }
        // 一行一行取出数据，直到遇到空行为止， 头部的格式 key: val\r\nkey: val\r\n....
        while (true)
        {
            std::string ret = buf->GetLinePop();
            // 2. 需要考虑的一些要素：缓冲区中的数据不足一行， 获取的一行数据超大
            if (ret.size() == 0)
            {
                if (buf->readable_size() > Max)
                {
                    _recv_status = RECV_HTTP_ERROR;
                    _resp_status = 414;
                    return false;
                }
                return true;
            }
            if (ret.size() > Max)
            {
                _recv_status = RECV_HTTP_ERROR;
                _resp_status = 414;
                return false;
            }
            if (ret == "\r\n" || ret == "\n")
            {
                break;
            }
            bool b = ParseHttpHeader(ret);
            if (b == false)
            {
                return false;
            }
        }
        _recv_status = RECV_HTTP_BODY;
        return true;
    }
    // 解析头部字段
    bool ParseHttpHeader(std::string &line)
    {
        if (line.back() == '\n')
            line.pop_back(); // 去掉末尾的换行符
        if (line.back() == '\r')
            line.pop_back(); // 去掉末尾的回车符
        size_t pos = line.find(": ");
        if (pos == std::string::npos)
        {
            _recv_status = RECV_HTTP_ERROR;
            _resp_status = 400;
            std::cout << "No3 match" << std::endl;
            return false;
        }
        std::string key = line.substr(0, pos);
        std::string value = line.substr(pos + 2);
        _request.SetHeader(key, value);
        return true;
    }
    // 接收正文
    bool RecvHttpBody(Buffer *buf)
    {
        if (_recv_status != RECV_HTTP_BODY)
            return false;
        // 1 获取请求正文长度
        size_t content_line = _request.ContentLength();
        if (content_line == 0)
        {
            _recv_status = RECV_HTTP_OVER;
            return true;
        }
        // 当前接收到的正文，其实就是放在_request._body中的数据
        size_t real_len = content_line - _request._body.size(); // 计算实际还需要的长度
        // 接收正文到body中
        // 1 如果数据已经全部接收完毕，则直接处理

        if (buf->readable_size() >= real_len)
        {
            _request._body.append(buf->current_read_pos(), real_len); // 将数据追加到body中 append:将数据添加到字符串末尾
            buf->move_read_pos(real_len);
            _recv_status = RECV_HTTP_OVER;
            return true;
        }
        // 2 如果数据未接收完毕，则先将数据取出来，然后继续接收
        _request._body.append(buf->current_read_pos(), buf->readable_size());
        buf->move_read_pos(buf->readable_size());
        return true;
    }

public:
    HttpContext() : _recv_status(RECV_HTTP_LINE), _resp_status(200) {}
    void ReSet()
    {
        _resp_status = 200;
        _recv_status = RECV_HTTP_LINE;
        _request.ReSet();
    }
    int RespStatus() { return _resp_status; }
    HttpRecvStatus RecvStatus() { return _recv_status; }
    HttpRequest &Request() { return _request; }
    // 接收并解析HTTP请求
    void RecvHttpRequest(Buffer *buf)
    {
        
        // 不同的状态，做不同的事情，但是这里不要break，因为处理请求行完毕后，应该立即处理头部，而不是退出等待新数据
        switch (_recv_status)
        {
        case RECV_HTTP_LINE:
            std::cout << "buf.size:" << buf->readable_size() << std::endl;
            RecvHttpLine(buf);
        case RECV_HTTP_HEAD:
            RecvHttpHeader(buf);
        case RECV_HTTP_BODY:
            RecvHttpBody(buf);
        }
        return;
    }
};

class HttpServer
{
private:
    using Handler = std::function<void(const HttpRequest &, HttpReponse *)>;
    using Handlers = std::vector<std::pair<std::regex, Handler>>;
    Handlers _get_route;
    Handlers _post_route;
    Handlers _put_route;
    Handlers _delete_route;
    std::string _basedir; // 静态资源目录
    TcpServer _server;

private:
    void ErrorHandler(const HttpRequest &request, HttpReponse *response)
    {
        std::string body;
        body += "<html>";
        body += "<head>";
        body += "<meta http - equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">";
        body += "<body>";
        body += "</head>";
        body += "<h1>";
        body += std::to_string(response->_status);
        body += " ";
        body += Util::StatuDesc(response->_status);
        body += "</h1>";
        body += "</body>";
        body += "</html>";
        response->SetContent(body, "text/html");
    }
    // 将HttpReponse中的要素按照http协议格式进行组织，发送
    void WriteReponse(const PtrConnection &con, HttpRequest &req, HttpReponse &rsp)
    {
        // 先完善头部字段
        if (req.Close() == true)
        {
            rsp.SetHeader("Connection", "close");
        }
        else
        {
            rsp.SetHeader("Connection", "keep-alive");
        }
        if (rsp._body.empty() == false && rsp.HasHeader("Content-Length") == false)
        {
            rsp.SetHeader("Content-Length", std::to_string(rsp._body.size()));
        }
        if (rsp._body.empty() == false && rsp.HasHeader("Content-Type") == false)
        {
            rsp.SetHeader("Content-Type", "application/octet-stream");
        }
        if (rsp._redirect_flag == true)
        {
            rsp.SetHeader("Location", rsp._redirect_url);
        }
        // 将rsp中的要素，按照http协议格式组织成字符串
        std::stringstream ss;
        ss << req._version << " " << std::to_string(rsp._status) << " " << Util::StatuDesc(rsp._status) << "\r\n";
        for (auto &header : rsp._headers)
        {
            ss << header.first << ": " << header.second << "\r\n";
        }
        ss << "\r\n";
        ss << rsp._body;
        // 发送数据
        con->Send(ss.str().c_str(), ss.str().size());
    }

    bool IsFileHandler(const HttpRequest &request)
    {
        // 判断是否是静态资源请求
        if (_basedir.empty()) // 没有设置静态资源目录，则认为不是静态资源请求
        {
            return false;
        }
        //  2 请求方法，必须是GET或者HEAD
        if (request._method != "GET" && request._method != "HEAD")
        {
            return false;
        }
        std::string req_path = _basedir + request._path; // 为了避免直接修改请求的资源路径
        std::cout << "请求路径" << req_path << std::endl;
        //  3 请求路径，必须是一个合法的目录或者一个存在的文件，判断不足
        // 如果本来就带有index.html文件名，这里的判断就不对
        if (Util::IsValidPath(req_path) == false)
        {
            return false;
        }
        // if (Util::IsDirectory(req_path) != true && Util::IsRegularFile(req_path) == false)
        // {
        //     return false;
        // }

        // 请求的资源必须存在，且是一个普通文件
        // 有一种请求比较特殊  ---目录：/ 这种情况给后面默认追加一个index.html文件
        if (req_path.back() == '/')
        {
            req_path += "index.html";
        }
        //  4 请求路径，必须是一个存在的文件
        if (Util::IsRegularFile(req_path) == false)
        {
            return false;
        }

        return true;
    }

    // 静态资源的请求处理
    bool FileHandler(const HttpRequest &request, HttpReponse *response)
    {
        std::string req_path = _basedir + request._path; // 为了避免直接修改请求的资源路径
        if (req_path.back() == '/')
        {
            req_path += "index.html";
        }
        bool ret = Util::ReadFile(req_path, &response->_body);
        if (ret == false)
        {
            return false;
        }
        std::string mime = Util::ExtMime(req_path);
        response->SetHeader("Content-Type", mime);
        return true;
    }
    // 功能性的请求分类处理
    void Dispatcher(HttpRequest &request, HttpReponse *response, Handlers &route_dispatcher)
    {
        // 在对应请求方法的路由器表中，查找是否含有对应资源请求的处理函数，有则调用，没有则发送404响应
        // 思想：路由表存储的时键值对，---正则表达式&处理函数
        // 使用正则表达式，对请求的资源路径进行正则匹配，匹配成功就使用对应函数进行处理
        //  /numbers/(\d+) 匹配数字 /users/(\w+) 匹配字母
        for (auto &route : route_dispatcher)
        {
            const std::regex &re = route.first;
            const Handler &handler = route.second;
            bool ret = std::regex_match(request._path, re); // 正则匹配
            if (ret == false)
            {
                continue;
            }
            handler(request, response);
            return;
        }
        response->_status = 404;
        return;
    }
    void Route(HttpRequest &request, HttpReponse *response)
    {
        // 对请求进行分辨，是一个静态资源请求，还是一个功能性请求
        // GET HEAD 都默认先认为是静态资源请求
        // 如果是静态资源请求，则进行就静态资源的处理
        // 功能性请求，则需要通过几个请求路由表来确定是否有对应的处理函数
        // 既不是静态资源请求，也不是功能性请求，则认为是错误请求，返回404

        // LOG_DEBUG("请求方法[%s] 请求路径 [%s]", request._method.c_str(), request._path.c_str());

        // std::cout << "请求方法" << request._method << std::endl;
        // std::cout << "请求路径" << request._path << std::endl;
        if (IsFileHandler(request) == true)
        {
            // 是一个静态资源请求，则进行静态资源的处理
            // LOG_DEBUG("静态资源请求");
            FileHandler(request, response);
        }
        else if (request._method == "GET" || request._method == "HEAD")
        {
            // LOG_DEBUG("请求方法[%s]", request._method.c_str());
            Dispatcher(request, response, _get_route);
        }
        else if (request._method == "POST")
        {
            Dispatcher(request, response, _post_route);
        }
        else if (request._method == "PUT")
        {
            Dispatcher(request, response, _put_route);
        }
        else if (request._method == "DELETE")
        {
            Dispatcher(request, response, _delete_route);
        }
        else
        {
            response->_status = 405; // 对于不支持的请求方法，返回405
        }
        return;
    }
    // 设置上下文
    void OnConnected(const PtrConnection &conn)
    {
        conn->SetContext(HttpContext());
        LOG_DEBUG("NEW CONNECTION %p", conn.get());
    }
    // 缓冲区数据解析+处理
    void OnMessage(const PtrConnection &conn, Buffer *buf)
    {
        while (true)
        {
            // 获取上下文
            HttpContext *context = conn->GetContext()->get<HttpContext>();
            // 通过上下文对缓冲区数据进行解析得到HttpRequest对象
            context->RecvHttpRequest(buf);
            HttpReponse response(context->RespStatus());
            HttpRequest &request = context->Request();
            if (context->RespStatus() >= 400)
            {
                // 进行错误响应，关闭连接
                ErrorHandler(request, &response);         // 填充一个错误的显示页面数据到rsp中
                WriteReponse(conn, request, response);    // 组织响应发送给客户端
                context->ReSet();                         // 重置上下文
                buf->move_read_pos(buf->readable_size()); // 出错了就把缓冲区数据清空
                conn->Shutdown();                         // 关闭连接
                return;
            }
            if (context->RecvStatus() != RECV_HTTP_OVER)
            {
                // 缓冲区数据不够，继续等待
                return;
            }
            
            // 请求路由+业务处理
            Route(request, &response);
            // 对HttpRespone进行组织并发送
            WriteReponse(conn, request, response);
            // 重置上下文
            context->ReSet();
            // 释放上下文
            if (response.Close() == true)
                conn->Shutdown(); // 短连接关闭连接，长连接保持连接
        }
        return;
    }

public:
    HttpServer(int port, int timeout = DELETE_TIEMOUT) : _server(port)
    {
        _server.EnableInactiveRelease(timeout);
        _server.SetConnectedCallback(std::bind(&HttpServer::OnConnected, this, std::placeholders::_1));
        _server.SetMessageCallback(std::bind(&HttpServer::OnMessage, this, std::placeholders::_1, std::placeholders::_2));
    }
    void SetBaseDir(const std::string &path)
    {
        assert(Util::IsDirectory(path) == true);
        _basedir = path;
    }
    void Get(const std::string &path, Handler handler)
    {
        _get_route.push_back(std::make_pair(std::regex(path), handler));
    }
    void Post(const std::string &path, Handler handler)
    {
        _post_route.push_back(std::make_pair(std::regex(path), handler));
    }
    void Put(const std::string &path, Handler handler)
    {
        _put_route.push_back(std::make_pair(std::regex(path), handler));
    }
    void Delete(const std::string &path, Handler handler)
    {
        _delete_route.push_back(std::make_pair(std::regex(path), handler));
    }
    void SetThreadCount(int count)
    {
        _server.SetThreadNum(count);
    }

    void Listen()
    {
        _server.Start();
    }
};